package cn.gson.school.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import cn.gson.school.dao.ImagesDao;
import cn.gson.school.entity.xitong.ImageEntity;
import cn.gson.school.entity.xitong.UserEntity;

@Service
public class ImagesService {

	Logger log = LoggerFactory.getLogger(getClass());

	@Value("${upload.dir}")
	private String uploadDir;

	@Autowired
	private ImagesDao dao;

	public ImageEntity save(ImageEntity att) {
		return dao.save(att);
	}

	public ImageEntity get(String imagePath) {
		return dao.findByImagePath(imagePath);
	}

	public ImageEntity get(Long attId) {
		return dao.findOne(attId);
	}

	public boolean drop(String filePath) throws FileNotFoundException {
		ImageEntity img = this.get(filePath);
		if (img != null) {
			return this.drop(img.getImageId());
		}
		throw new FileNotFoundException("附件不存在！");
	}

	/**
	 * 删除附件
	 * 
	 * @param attId
	 * @return
	 * @throws FileNotFoundException
	 */
	public boolean drop(Long attId) throws FileNotFoundException {
		ImageEntity img = dao.findOne(attId);
		if (img == null) {
			throw new FileNotFoundException("附件不存在！");
		}
		File f = new File(uploadDir, img.getImagePath());
		if (!f.exists()) {
			throw new FileNotFoundException("文件不存在！");
		}
		// 删除
		f.deleteOnExit();
		dao.delete(img);
		return true;
	}

	/**
	 * 上传文件的公共服务方法
	 * 
	 * @param user
	 *            用户信息
	 * @param type
	 *            类型信息
	 * @param file
	 *            文件对象
	 * @return
	 * @throws Exception
	 */
	public ImageEntity upload(UserEntity user, String type, MultipartFile file,String id) throws Exception {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
			String dateDir = sdf.format(new Date());
			// 获取文件后缀
			String ext = FilenameUtils.getExtension(file.getOriginalFilename());
			// 构建新的文件名称
			String newFileName = UUID.randomUUID().toString() + "." + ext;
			String filePath = String.format("%s%s/%s", uploadDir, type, dateDir);
			// 文件存储的目录
			File fileDir = new File(filePath);
			if (!fileDir.exists()) {
				// 如果目录不存在，则创建出来
				fileDir.mkdirs();
			}
			ImageEntity img = new ImageEntity();
			if(!id.equals("")) {
				img.setImageId(Long.valueOf(id));
			}
			img.setImageName(file.getOriginalFilename());
			img.setImageSize(file.getSize());
			img.setImageType(ext);
			img.setContentType(file.getContentType());
			img.setImagePath(String.format("%s/%s/%s", type, dateDir, newFileName));
			img.setImageTime(new Date());
			if(user != null) {
				img.setUserId(user);
			}
			
			// 存储文件信息到数据库
			this.save(img);

			file.transferTo(new File(fileDir, newFileName));
			return img;
		} catch (IllegalStateException | IOException e) {
			log.error("上传失败！", e);
			throw new Exception("上传失败！", e);
		}
	}
}